﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ClientAppraise.ViewModels.Validator
{
    public sealed class UserNameAttribute : ValidationAttribute
    {
        readonly int max = 5;
        readonly int min = 5;
        public UserNameAttribute(int min = 6, int max = 16)
        {
            this.max = max;
            this.min = min;
        }
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            if (value == default) return ValidationResult.Success;

            var strValue = value.ToString();

            if (string.IsNullOrEmpty(strValue)) return ValidationResult.Success;


            if (strValue.Length < min || strValue.Length > max)
            {
                return new($"长度只能为{min}到{max}位");
            }

            if (!Regex.IsMatch(strValue, @"^([A-Za-z_0-9]{" + $"{min},{max}}})$"))
            {
                return new("只能是字母、下划线、数字组合");
            }

            return ValidationResult.Success;
        }
    }

}
